package main
import (
	"fmt"
	"net"
	"os"
	"io"
	"time"
)

func main(){
	
	defer time.Sleep(time.Second * 3)
	
	filename := `K:\程序设计\20小时快速入门go语言视频\08\18_段子爬虫：把内容存储到文件中.avi`
	
	fmt.Println("请输入文件名(含路径)：")
	fmt.Scan(&filename)
	
	fileinfo, err := os.Stat(filename)
	if err != nil{
		fmt.Println("文件不存在！\nStat err : ", err)
		return
	}
	
	/*连接服务器*/
	conn, err := net.Dial("tcp", "192.168.0.2:8000")
	if err != nil{
		fmt.Println("Dial err : ", err)
		return
	}
	defer conn.Close()
	/*向服务器发送文件名*/
	var sum int
	sum, err = conn.Write([]byte(fileinfo.Name()))
	if err != nil{
		fmt.Println("Write err : ", err)
		return
	}
	
	/*接收服务器端反馈*/
	buf := make([]byte, 1024 * 4)

	sum, err = conn.Read(buf)
	if err != nil{
		fmt.Println("Read2 err : ", err)
		return
	}
	if "OK" == string(buf[:sum]){
		fmt.Println("服务器反馈OK")
	}else{
		fmt.Println("服务器反馈不OK")
	}
	
	f, err2 := os.Open(filename)
	if err != nil{
		fmt.Println("读取失败, err2 : ", err2)
		return
	}
	defer f.Close()
	for{
		sum, err = f.Read(buf)
		if err != nil{
			if err == io.EOF{
				fmt.Println("文件发送完毕")
				break
			}else{
				fmt.Println("文件发送失败")
			}
			return
		}
		conn.Write(buf[:sum])
	}
}